import time
import datetime
import threading
from pynput import mouse, keyboard
from ctypes import *
import win32api,win32gui,win32con
import win32clipboard
import win32com.client
import pythoncom
import os

OpenFlag = False

def test1(dm):
    intX=0
    intY=0
    pos = [0,0,0]
    while True:
        if OpenFlag:
            
            try:
                time.sleep(0.2)
                pos = dm.FindPic(0,0,1920,1080,"ffo.bmp","000000",0.9,0,intX,intY)
                print("搜索到横坐标：" + str(pos[1]))
                if pos[1]>0:
                    print("找到准备，鼠标点击")
                    dm.MoveTo(pos[1],pos[2])
                    dm.LeftClick()
                    dm.MoveTo(0,0)
                    print("找到准备，点击完成，切换窗口")
                    dm.KeyDownChar("alt")
                    dm.KeyDownChar("tab")
                    dm.KeyUpChar("tab")
                    dm.KeyUpChar("alt")
                pass
            except:
                pass
            
            pass
        pass
    pass

def main():
    print("准备中。。。")
    pythoncom.CoInitialize() # 调用大漠必须的
    try:
        dm = win32com.client.Dispatch('dm.dmsoft')  # 调用大漠插件
        dm_ret = dm.SetPath(os.getcwd()+"/scr") # 设置大漠插件所用资源目录
        pass
    except:
        r_v = os.system("regdm.bat") 
        dm = win32com.client.Dispatch('dm.dmsoft')  # 调用大漠插件
        dm_ret = dm.SetPath(os.getcwd()+"/scr") # 设置大漠插件所用资源目录
        print("首次打开，需要关闭重新打开")
        pass

    # 通过 target=函数名 的方式定义子线程
    t1 = threading.Thread(target=test1,args=(dm,))  # 通过target指定子线程要执行的任务。可以通过args=元组 来指定test1的参数。
    t1.start()  # 只有在调用start方法后才会创建子线程并执行


    def on_press(key):
        global OpenFlag

        print(key)
        #开始
        if hasattr(key, 'char') and key.char == "q":
            print("开始")
            OpenFlag=True
            pass
        #结束
        if hasattr(key, 'char') and key.char == "w":
            print("结束")
            OpenFlag=False
            pass
        pass
    def on_release(key):
        pass
    # 监听键盘按键
    with keyboard.Listener(on_press=on_press, on_release=on_release) as listener:
        print("按Q开始")
        listener.join()

if __name__ == "__main__":
    main()